import cv2
import numpy as np

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

while True:
    ret, image = cap.read()
    if not ret:
        break
    # 转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 应用高斯模糊
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 使用Canny算法进行边缘检测
    edges = cv2.Canny(blurred, 50, 150)
    cv2.imshow('Edges', edges)
    # 寻找轮廓
    _, contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 筛选出黑色矩形框
    for contour in contours:
        # 计算轮廓的近似多边形
        epsilon = 0.02 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        
        # 如果近似多边形有4个顶点，则认为是矩形
        if len(approx) == 4:
            # 获取矩形的外顶点
            x, y, w, h = cv2.boundingRect(contour)
            rect_points = [((x, y), (x + w, y), (x + w, y + h), (x, y + h))]
            break

    # 绘制轮廓
    cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)

    # 绘制矩形顶点
    for point in rect_points:
        for p in point:
            cv2.circle(image, p, 5, (255, 0, 0), -1)
    # 显示图像
    cv2.imshow('Image with Rectangle', image)
    cv2.waitKey(1)

cv2.destroyAllWindows()